package com.yz.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Component
@EnableWebSocket ////开启webScoket
@ServerEndpoint(value = "/mywebsocket/{userName}") //设置socket服务端的地址和参数
public class MyServerEndpoint extends ServerEndpointExporter{

		//声明一个数组来存储目前和服务端建立连接的客户端session对象，key是session的id(唯一标识)
		public static Map<String,Session> map = new HashMap<String,Session>();
	
		@OnOpen
		public void onOpen(Session session,@PathParam("userName")String userName) {
			map.put(session.getId(), session);
			allSendMsg(userName+"进入聊天室了");
		}
		
		@OnClose
		public void onClose(Session session,@PathParam("userName")String userName) {
			map.remove(session.getId());
			allSendMsg(userName+"退出聊天室了");
		}
		
		@OnMessage
		public void onMessage(Session session,String message,@PathParam("userName")String userName) {
			allSendMsg(userName+":"+message);
		}
		
		/**
		 * 群发
		 */
		public void allSendMsg(String msg) {
				try {
					for(String key:map.keySet()) {
					map.get(key).getBasicRemote().sendText(msg);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
}
